﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;


   public class NonUniqueKeyDictionary<K,V> : IDictionary<K,List<V>>
   {

      Dictionary<K,List<V>> _internal = new Dictionary<K,List<V>>();

      public void Add(K key, V value)
      {
         if (_internal.ContainsKey(key))
         {
            _internal[key].Add(value);
         }
         else
         {
            _internal.Add(key, new List<V>(){value});
         }
      }

      public bool ContainsKey(K key)
      {
         return _internal.ContainsKey(key);
      }

      public ICollection<K> Keys
      {
         get { return _internal.Keys; }
      }

      public bool Remove(K key)
      {
         return _internal.Remove(key);
      }

      public bool TryGetValue(K key, out List<V> value)
      {
         List<V> outParam;
         var result = _internal.TryGetValue(key, out outParam);

         value = outParam;
         return result;
      }

      public ICollection<V> Values
      {
         get { throw new NotImplementedException(); }
      }

      public List<V> this[K key]
      {
         get { return _internal[key]; }
         set{ _internal[key]= value;}
      }

      public bool TryGetValue(K key, out V value)
      {
         List<V> list;
         _internal.TryGetValue(key, out list);

         if (list != null)
         {
            value = list.FirstOrDefault();

            return value != null;
         }
 
         value = default(V);
         return false;

      }

      public void Add(K key, List<V> value)
      {
         _internal.Add(key,value);
      }

      ICollection<List<V>> IDictionary<K, List<V>>.Values
      {
         get { return _internal.Values; }
      }


      public void Add(KeyValuePair<K, List<V>> item)
      {
         _internal.Add(item.Key,item.Value);
      }

      public void Clear()
      {
         _internal.Clear();
      }

      public bool Contains(KeyValuePair<K, List<V>> item)
      {
         return _internal.Contains(item);
      }

      public void CopyTo(KeyValuePair<K, List<V>>[] array, int arrayIndex)
      {
         _internal.ToArray().CopyTo(array,arrayIndex);
      }

      public int Count
      {
         get { return _internal.Count; }
      }

      public bool IsReadOnly
      {
         get { return false; }
      }

      public bool Remove(KeyValuePair<K, List<V>> item)
      {
         return _internal.Remove(item.Key);
      }


      public IEnumerator<KeyValuePair<K, List<V>>> GetEnumerator()
      {
         return _internal.GetEnumerator();
      }


      IEnumerator IEnumerable.GetEnumerator()
      {
         return _internal.GetEnumerator();
      }

   }

